class Image < ActiveRecord::Base
  attr_accessor :base_64_encoded_data

  # Callback
  before_create :generate_uuid, if: :url_nil?
  after_destroy :delete_image_file

  private
    def generate_uuid
      uuid = UUIDTools::UUID.timestamp_create().to_s
      image_content = self.base_64_encoded_data.gsub(/data:image\/([a-zA-Z]+);base64,/, '')
      self.url = "/assets/images/#{Date.today}/#{uuid}.jpg"
      file_dir = "#{ENV["PWD"]}/public/assets/images/#{Date.today}"

      Dir.mkdir file_dir unless Dir.exist? file_dir

      File.open("#{file_dir}/#{uuid}.jpg", 'wb') do|f|
        f.write(Base64.decode64(image_content))
      end
    end

    def url_nil?
      self.url.nil?
    end

    def delete_image_file
      file_path = "#{ENV['PWD']}/public/#{url}"
      if File.exist?(file_path)
        File.delete(file_path)
      end
    end
end